import Koa, { Context } from 'koa'
import { trace } from './config/logger'

const app = new Koa()

export default app

export namespace ServiceInterfaceApplications {
  export type ServiceInterfaceFun = (ctx: Context, reqBody?: any) => void | Promise<void>

  export interface ServiceInterface {
    readonly serviceInterfaceNo: string
    readonly fun: ServiceInterfaceFun
    readonly serviceInterfaceDesc?: string
  }
}

export interface Application {
  init(app: Koa): void | Promise<void>
  service(ctx: Context): void | Promise<void>
  destroy(app: Koa): void | Promise<void>
}

export class ServiceInterfaceApplication implements Application {
  serviceInterfaceMap: Map<string, ServiceInterfaceApplications.ServiceInterface> = new Map()

  init (app: Koa): void {

  }

  async service (ctx: Koa.Context) {
    const service = ctx.header.service
    const si = this.serviceInterfaceMap.get(service)
    if (si && si.fun instanceof Function) {
      trace.info(`invoking service: [${service}] start`)
      await si.fun(ctx, ctx.request.body || {})
      trace.info(`invoking service: [${service}] end`)
    } else {
      trace.info(`service: [${service}] not found`)
      ctx.throw(404, `service: [${service}] not found`)
    }
  }

  destroy (app: Koa): void {

  }

  addServiceInterface (si: ServiceInterfaceApplications.ServiceInterface) {
    if (this.serviceInterfaceMap.has(si.serviceInterfaceNo)) {
      throw new Error(`serviceInterfaceNo: [${si.serviceInterfaceNo}] 重复`)
    }
    this.serviceInterfaceMap.set(si.serviceInterfaceNo, si)
    return this
  }
}
